//
//  ReplyMainTableViewCell.swift
//  Gaoloumi
//
//  Created by Jasper on 4/3/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import AVOSCloud

class ReplyMainTableViewCell: UITableViewCell, SDPhotoBrowserDelegate {
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var louLabel: UILabel!
    @IBOutlet weak var userNameButton: UIButton!
    @IBOutlet weak var lineHeight: NSLayoutConstraint!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var imageView1: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!
    @IBOutlet weak var imageView3: UIImageView!
    @IBOutlet weak var clickContLabel: UILabel!
    @IBOutlet weak var replyCountLabel: UILabel!
    @IBOutlet weak var updateTimeLabel: UILabel!
    @IBOutlet weak var imageHeight: NSLayoutConstraint!
    
    var cellTop: Topic?
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        lineHeight.constant = 0.5
        louLabel.layer.cornerRadius = 2
        louLabel.layer.masksToBounds = true
        
        userImageView.layer.cornerRadius = 3
        userImageView.layer.masksToBounds = true
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(ReplyMainTableViewCell.tapGesture(_:)))
        imageView1.addGestureRecognizer(tap)
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(ReplyMainTableViewCell.tapGesture(_:)))
        imageView2.addGestureRecognizer(tap2)
        let tap3 = UITapGestureRecognizer(target: self, action: #selector(ReplyMainTableViewCell.tapGesture(_:)))
        imageView3.addGestureRecognizer(tap3)
    }
    
    func refreshView(_ topic: Topic) {
        cellTop = topic
        titleLabel.text = topic.title
        userNameButton.setTitle(topic.user?.username, for: .normal)
        clickContLabel.text = "\(topic.clickCount)"
        replyCountLabel.text = "\(topic.replyCount)"
        contentLabel.text = topic.content
        let imgFile = topic.user!.object(forKey: "avatar") as? AVFile
        if imgFile != nil {
            userImageView?.kf.setImage(with: URL(string: (imgFile?.url)!)!,
                                   placeholder: DataCenter.sharedInstance.placeholderImage,
                                   options: nil,
                                   progressBlock: { receivedSize, totalSize in
                                    
                },
                                   completionHandler: { image, error, cacheType, imageURL in
                                    
            })
            
            
        } else {
            userImageView.image = UIImage(named: "defaultUser")
        }
        
        let date = topic.object(forKey: kTopicKeyLastReplyTime) as! Date
        updateTimeLabel.text = DataCenter.sharedInstance.friendlyTime(date)
        
        var imgArray = [imageView1, imageView2, imageView3]
        var i = 0
        if topic.contentImage == nil || topic.contentImage?.count == 0 {
            imageHeight.constant = 0
        } else {
            let width = (UIScreen.main.bounds.width-8*4)/3
            let intWidth = Int(width)*2
            imageHeight.constant = width
            for image in topic.contentImage! {
                let urlstr = image.url
                if urlstr != nil {
                    let urlCon = "\(urlstr)?imageView/1/w/\(intWidth)/h/\(intWidth)"
                    let imageView = imgArray[i]
                    
                    imageView?.kf.setImage(with: URL(string: urlCon),
                                               placeholder: DataCenter.sharedInstance.placeholderImage,
                                               options: nil,
                                               progressBlock: { receivedSize, totalSize in
                                                
                        },
                                               completionHandler: { image, error, cacheType, imageURL in
                                                
                    })
                    
                    i += 1
                    imageView?.isUserInteractionEnabled = true
                }
            }
        }
        
        imgArray.removeSubrange(Range(0..<i))
        for imageView in imgArray {
            imageView?.image = nil
            imageView?.isUserInteractionEnabled = false
        }
    }
    
    func tapGesture(_ sender: UITapGestureRecognizer) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self.contentView
        browser.imageCount = (cellTop!.contentImage?.count)!
        browser.currentImageIndex = ((sender.view?.tag)!-100)
        browser.delegate = self
        browser.show()
    }

    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let img = self.contentView.viewWithTag(100+index) as! UIImageView
        return img.image
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let url = cellTop?.contentImage![index].url
        return URL(string: url!)
    }
}
